package com.doit.day01.op

object _02_平均温度案例 {
  def main(args: Array[String]): Unit = {
    //有3天得数据
    val d1 = Array(("beijing", 28.1), ("shanghai", 28.7), ("guangzhou", 32.0), ("shenzhen", 31.0))
    val d2 = Array(("beijing", 27.3), ("shanghai", 30.1), ("guangzhou", 33.3))
    val d3 = Array(("beijing", 28.2), ("shanghai", 29.1), ("guangzhou", 32.0), ("shenzhen", 32.0))

    //需求：求出三天中，每个地方得平均温度

    /**
    ("beijing", 28.1)
    ("beijing", 27.3)
    ("beijing", 28.2)
     ==》(beijing,平均温度)
     */
    //1.把三天得数据全部放在一起
    val allData: Array[(String, Double)] = d1 ++ d2 ++ d3
    //2.要把北京得温度放在一起，把上海得放在一起，把广州得放在一起
    val map: Map[String, Array[(String, Double)]] = allData.groupBy(_._1)

    //转换格式
    val cityAndTemp: Map[String, Array[Double]] = map.map(map => {
      val city: String = map._1
      val value: Array[(String, Double)] = map._2
      //把数组里面所有得元素全部变成了温度
      val tempArr: Array[Double] = value.map(elem => elem._2)
      (city, tempArr)
    })

    //3.求平均值
    val res: Map[String, Double] = cityAndTemp.map(tp => {
      val city: String = tp._1
      val arr: Array[Double] = tp._2
      val sumTemp: Double = arr.sum
      val count: Int = arr.size
      val avg: Double = sumTemp / count

      (city, avg.formatted("%.2f").toDouble)
    })

    res.foreach(println)




  }

}
